#!/usr/bin/python
## Requires ElementTree 1.3+, which is in Python 2.7+.
##
## Usage: 
## If run without arguments, script reads from stdin and writes to stdout.
## To specify input and (optional) output files, run as
##      $ ./atom2html.py feed.xml [basename]
## where basename is the base of the output file name(s).
## If no basename is specified, output is written to stdout.
##
## Modify variable chunk_size below to specify maximum number of feed entries
## per output file.

chunk_size = 250

import codecs, os, sys
from xml.sax.saxutils import unescape
import xml.etree.ElementTree as ET

PY3 = sys.version > '3'

def write_head(ofile, title, subtitle, link, updated):
	s = """<html><head><meta http-equiv='content-type' content='text/html; charset=UTF-8'>
<style type='text/css'>
html,body { font-family: Helvetica,Arial,sans-serif; }
body { margin: 1.5em 10%%; }
.entry { border-top: 1px solid gray; }
h1 a:link, h1 a:active, h1 a:visited, h3 a:link, h3 a:active, h3 a:visited { color: black; text-decoration: none; }
h1 a:hover, h3 a:hover { text-decoration: underline; }
.entry h3 { margin-bottom: 0.5em; }
.entryauthor, .entrypub { color: #505050; }
.entrypub, .entrylink { display: block; float: right; }
.entrycontent { margin: 1em auto; }
</style>
<title>Google Reader feed archive: %s</title></head>
<body>
<h1><a href='%s'>%s</a></h1>
<h2>%s</h2>
<p><em>Google Reader Feed Archive</em> &mdash; Last updated: %s</p>
""" % (title, link, title, subtitle, updated)
	ofile.write(s)
	return

def open_outfile(filename):
	if os.path.exists(filename):
		sys.exit("File %s already exists. Stopping script." % filename)
	elif PY3:
		return open(filename, "w")
	else:	
		return codecs.open(filename, "w", "utf8")

basename = None

if len(sys.argv) < 2:
	f = sys.stdin
else:
	f = open(sys.argv[1])
	if len(sys.argv) > 2:
		basename = sys.argv[2]

tree = ET.parse(f)
root = tree.getroot()
ns = "{http://www.w3.org/2005/Atom}"

feedtitle = root.findtext(ns+"title")
feedsubtitle = root.findtext(ns+"subtitle")
feedlink = root.find("./"+ns+"link[@rel='alternate']")
if feedlink == None:
	feedlink = ""
else:
	feedlink = feedlink.get("href")
feedupdated = root.findtext(ns+"updated")
entries = root.findall(ns+"entry")

file_num = 1
entry_num = 0

if basename:
	output = open_outfile(basename + ".html")
else:
	if PY3:
		output = sys.stdout
	else:
		output = codecs.getwriter('utf8')(sys.stdout)

write_head(output, feedtitle, feedsubtitle, feedlink, feedupdated)

for e in entries:
	if basename and output.closed:
		file_num += 1
		output = open_outfile(basename + str(file_num) + ".html")
		write_head(output, feedtitle, feedsubtitle, feedlink, feedupdated)
	title = e.findtext(ns+"title")
	author = e.find(ns+"author")[0].text
	published = e.findtext(ns+"published")
	link = e.find(ns+"link")
	if link != None:
		link = link.get("href")
	content = e.find(ns+"content")
	summary = e.find(ns+"summary")
	if content != None:
		content = unescape(content.text)
	elif summary != None:
		content = unescape(summary.text)
	else:
		content = "[No content]"
	
	s = "<div class='entry'><h3 class='entrytitle'><a href='%s'>%s</a></h3>" % (link, title)
	s += "<span class='entryauthor'>%s</span>" % author
	s += "<span class='entrypub'>%s</span>" % published
	s += "<div class='entrycontent'>%s</div></div>\n" % content
	output.write(s)
	entry_num += 1
	if basename and entry_num % chunk_size == 0:
		output.write("</body></html>")
		output.close()
		
if basename and entry_num % chunk_size != 0:
	output.write("</body></html>")
	output.close()

if not basename:
	output.write("</body></html>\n")
